

import os
import sys
import time
import multiprocessing as mp

import rpyc
from rpyc.utils import server

import dexen
from dexen.system.common import service
from dexen.system.common.service import DexenAddr
from dexen.system.node.slave import service as slave_srvc
from dexen.system.node.master import service as master_srvc
from rpyc.utils.factory import DiscoveryError

#===============================================================================
# Globals
#===============================================================================
masters = {}
slaves = {}
ns_slots = None # Number of slave slots
nm_slots = None # Number of master slots
#===============================================================================
# Service
#===============================================================================
class NodeService(dexen.Service):
        
    def create_master(self, master_name):
        print "{0} is being created".format(master_name)
        proc = mp.Process(target=master_srvc.start, name=master_name, 
                          args=(master_name, name, reg_addr)) 
        masters[master_name] = proc
        proc.start()
        print "{0} has started running with id:{1}".format(master_name, proc.pid)
        time.sleep(0.1)
        
    def create_slave(self, slave_name):
        proc = mp.Process(target=slave_srvc.start, name=slave_name, 
                          args=(slave_name, name, reg_addr)) 
        slaves[slave_name] = proc
        proc.start()
        time.sleep(0.1)
    
    def is_alive(self):
        pass
    
    def n_slave_slots(self):
        return ns_slots
    
    def n_master_slots(self):
        return nm_slots
    
    def test(self):
        pass

def start(reg_ip, reg_name, n_slave_slots, n_master_slots=1):
    global start_time, name, reg_addr, ns_slots, nm_slots
    ns_slots = n_slave_slots
    nm_slots = n_master_slots
    print "reg_ip:{0}, reg_name:{1}".format(reg_ip, reg_name)
    try:
        host_list = rpyc.discover(reg_name, reg_ip)
        (ip, port) = host_list[0]
    except DiscoveryError:
        try:
            print "I am in first discovery error"
            (ip, port) = rpyc.discover(reg_name)[0]
        except DiscoveryError:
            print "I am in second discovery error"
            ip = reg_ip
            port = service.REGISTRY_PORT
            
    reg_addr = DexenAddr(ip, port)
    svr = server.ThreadedServer(NodeService, 
                                protocol_config=service.default_config)
    my_ip = service.get_my_ip()
    my_addr = DexenAddr(my_ip, svr.port)
    conn = reg_addr.get_conn()
    start_time = time.time()
    name = conn.root.register_node(start_time, my_addr)
    svr.start()
    
    
#===============================================================================
# Main
#===============================================================================
def main():
    pass


if __name__ == "__main__":
    main()
    
